package org.github.core.spring.util;

import java.util.Locale;
import org.springframework.context.MessageSource;
import static cn.hutool.extra.spring.SpringUtil.getBean;
import static com.google.common.base.MoreObjects.firstNonNull;
import static org.springframework.context.i18n.LocaleContextHolder.getLocale;

public interface MessageSourceUtil {
    static String i18n(String code, Object[] args, Locale locale) {
        try {
            return getInstance().getMessage(code, args, code, firstNonNull(locale, getLocale()));
        } catch (Exception ignore) {
            return code;
        }
    }

    static String i18n(String code, Object[] args) {
        return i18n(code, args, null);
    }

    static String i18n(String code) {
        return i18n(code, null, null);
    }

    static MessageSource getInstance() {
        return SingletonInstance.instance;
    }

    class SingletonInstance {
        private static final MessageSource instance = getBean(MessageSource.class);
    }
}
